<?php

namespace app\admin\service;

use app\admin\model\UM as UM;
use app\common\job\MemberMutedExpiration;
use app\common\model\Member;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Queue;

/**
 * Class MemberMutedService
 * @package app\member\service
 */
class MemberMutedService
{
    private $mutedLengthType;

    public function __construct()
    {
        $this->mutedLengthType = Config::get('member.mutedLengthType', []);
    }

    /**
     * 更新
     * @param \app\admin\model\UM $user
     * @param int $id
     * @param array $params
     * @return \app\common\model\Member
     */
    public function modify(UM $user, int $id, array $params): Member
    {
        $now = time();
        $params['muted'] ??= '0';

        $record = Member::field(true)
            ->with(['memberInfo'])
            ->where('id', $id)
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该用户不存在或已被删除');
        }

        if ($params['muted'] == 1) {

            $params['mutedUserId'] = $user->id;
            $params['mutedActionTime'] = $now;
            $params['mutedLength'] ??= 0;
            $params['mutedCause'] ??= null;

            if (!is_numeric($params['mutedLength'])) {
                throw new ValidateException('请选择禁言时间');
            }
            if (is_blank($params['mutedCause'])) {
                throw new ValidateException('请输入禁言原因');
            }

            $mutedLengthType = $this->mutedLengthType[$params['mutedLength']] ?? end($this->mutedLengthType);
            $params['mutedTime'] = $mutedLengthType['mutedTime'] == 0 ? 0 : ($now + $mutedLengthType['mutedTime']);
        } else {

            $params['mutedUserId'] = 0;
            $params['mutedActionTime'] = 0;
            $params['muted'] = 0;
            $params['mutedLength'] = 0;
            $params['mutedTime'] = 0;
            $params['mutedCause'] = '';
        }

        $record->mutedUserId = $params['mutedUserId'];
        $record->mutedActionTime = $params['mutedActionTime'];
        $record->muted = $params['muted'];
        $record->mutedLength = $params['mutedLength'];
        $record->mutedTime = $params['mutedTime'];
        $record->mutedCause = $params['mutedCause'];
        $record->save();

        // 如果是律师，那么可以修改证书注册时间
        if ($record->type == '1' && !is_null($record->memberInfo)) {
            if (is_numeric($params['practiceTime'] ?? null)) {
                $record->memberInfo->practiceTime = $params['practiceTime'];
                $record->memberInfo->save();
            }
        }

        // 添加定时任务，到时间后自动解除禁言
        if ($record->muted == 1 && $record->mutedLength < 5) {
            $job_data = ['id' => $record->id];
            Queue::later($record->mutedTime - $now - 1, MemberMutedExpiration::class, $job_data);
        }

        // TODO 隐藏问题，这里变了， 不兼容以前的问题
        // $this->getMemberAskDao()
        //     ->updateActiveByClosure(fn($query) => $query->where('memberId', $record->id)->where('status', '1')->where('isDel', '0'), ['isDel' => 1]);

        return $record;
    }

    /**
     * 禁言时间到期后尝试解除禁言
     * @param $id
     * @return void
     */
    public function tryMutedExpiration($id): void
    {
        if (!is_id($id)) {
            return;
        }

        $record = Member::field(['id', 'muted', 'mutedTime'])->where('id', $id)->find();
        if (!$record) {
            return;
        }

        if ($record->muted == 0) {
            return;
        }

        if ($record->mutedLength == 5) {
            return;
        }

        if ($record->mutedTime > time()) {
            return;
        }

        // 解除禁言
        $record->muted = 0;
        $record->mutedLength = 0;
        $record->mutedTime = 0;
        $record->mutedCause = '';
        $record->mutedUserId = 0;
        $record->mutedActionTime = 0;
        $record->save();
    }
}
